package com.limh.gobang.service.resource

import android.content.Context
import android.util.Log
import com.limh.gobang.base.Consts
import com.limh.gobang.bean.Fight
import com.limh.gobang.bean.MsgEvent
import com.limh.gobang.bean.Type
import com.limh.gobang.bean.User
import com.limh.gobang.service.utils.HttpContext
import com.limh.gobang.service.utils.StreamToolkit
import com.limh.gobang.utils.GsonUtils
import com.limh.gobang.utils.SpUtils
import org.greenrobot.eventbus.EventBus
import java.io.OutputStreamWriter

/**
 * @function 认证用户信息
 * @author limh
 * @date 2018/4/28 9:30
 */
class ResourceAddressHandler(private var context: Context) : IResourceUriHandler {
    private val TAG = "ResourceAddressHandler"
    val suffix = "/auth"

    override fun accept(uri: String?): Boolean {
        return uri!!.startsWith(suffix)
    }

    override fun handle(uri: String?, httpContext: HttpContext?) {
        val startIndex = suffix.length
        val assetsPath = uri!!.substring(startIndex)
        Log.d(TAG, "handle=$assetsPath")

        val ins=httpContext!!.underlySocket!!.getInputStream()
        var readLine=""
        while (StreamToolkit.readContent(ins).apply { readLine = this!! } != null) {
            if (readLine == "") {
                Log.d(TAG, "header line finish")
                break
            }
            Log.d(TAG, "消息内容=$readLine")

            val msg = GsonUtils.str2Bean(readLine, MsgEvent::class.java)
            EventBus.getDefault().post(msg)

            var response=""
            when(msg.code){
                Type.TYPE_RQ_AUTH->{
                    val user=GsonUtils.str2Bean(SpUtils.get(context,Consts.SP_USER,"") as String,User::class.java)
                    val msgEvent=MsgEvent()
                    msgEvent.any=user
                    msgEvent.code = Type.TYPE_RS_AUTH
                    response = GsonUtils.bean2Str(msgEvent)
                }
            }

            Log.i(TAG, "响应消息：$response")
            val osw = OutputStreamWriter(httpContext.underlySocket!!.getOutputStream(),Charsets.UTF_8)
            val sb = StringBuilder()
            sb.append("HTTP/1.1 200 OK\r\n")
            sb.append("Connection: keep-alive\r\n")
            sb.append("Content-length: ${response.toByteArray(Charsets.UTF_8).size}\r\n")
            sb.append("${StreamToolkit.addContentType(assetsPath)}\r\n")
            sb.append("\r\n")
            sb.append("$response\r\n")
            osw.write(sb.toString())
            osw.flush()
            Log.d(TAG,"服务器响应了消息")
        }
    }
}